var WxParse = require('../../wxParse/wxParse.js');
//获取应用实例
var app = getApp();
const bgMusicAudioContext = wx.getBackgroundAudioManager();
Page({
  data: {
    toggleType: 'detail',
    autoplay: true,
    interval: 3000,
    duration: 1000, 
    isShowModal: false,
    buyNumber: 1,
    modalOperaType: "",
    cartNumber: 0,
    videoShow: false,
    chooseGuige: {   
    },
    isShowshare: false,
    isShowposter: false,
    goodType: 'group'
  },
  onLoad: function (e) {
    var that = this;
    if (e && e.scene) {
      var scene = decodeURIComponent(e.scene).split('&');
      console.log(scene);
      var secneObj = {};
      for (var i = 0; i < scene.length; i++) {
        var arr = scene[i].split('=');
        var key = arr[0];
        secneObj[key] = arr[1];
      }
      e = secneObj;
    }
    console.log(e);
    var goodId = '', type = '';
    if (e && e.goodid) {
      goodId = e.goodid;
      that.setData({
        goodId: goodId
      })
    }
    if (e && e.type) {
      type = e.type;
      that.setData({
        type: type,
      })
    }
    if (e && e.mid) {
      that.setData({
        mid: e.mid
      })
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    var res = wx.getSystemInfoSync();
    that.setData({
      winW: res.windowWidth,
      winH: res.windowHeight
    })
    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        if (plumSession != '') {
          console.log('查询到登录信息');
          that.getSlient();
          var mid = that.data.mid ? that.data.mid : '';
          app.globalData.requestUrl = app.getNewRequestUrl(mid);
          that.goodsDetail();
          app.contactData(that); 
          that.setData({
            isHasunionid: app.globalData.isHasunionid,
            haveVcmCard: app.globalData.haveVcmCard
          })
        } else {
          console.log('未查询到登录信息');
          app.wechatSq(that);
        }
      }
    } else {
      that.getSlient();
      var mid = that.data.mid ? that.data.mid : '';
      app.globalData.requestUrl = app.getNewRequestUrl(mid);
      that.goodsDetail();
      app.contactData(that); 
      that.setData({
        isHasunionid: app.globalData.isHasunionid,
        haveVcmCard: app.globalData.haveVcmCard
      })
    }
  },
  onShow:function(){
    var that = this;
  },
  initPage: function(){
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient:function(){
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient:'';
    that.setData({
      slient: slient
    })
  },
  // 客服回复组件间传值
  getreplyData: function (e) {
    console.log(e.detail);
    this.setData(e.detail);
  },
  onReady: function () {
    var that = this;
    that.videoContext = wx.createVideoContext('myVideo');
  },
  onHide: function () {
    this.hideVideo();
  },
  //播放视频
  playVideo: function (e) {
    var that = this;
    if (app.globalData.isPlay) {
      bgMusicAudioContext.stop();
      app.globalData.curInfoMusicid = '';
      app.globalData.isPlay = false;
      app.globalData.isPlaynew = 'new';
    } 
    that.setData({
      isShowVideo: true
    });
    that.videoContext.play();
  },
  // 关闭视频
  hideVideo: function () {
    var that = this;
    that.setData({
      isShowVideo: false
    })
  },
  goodsDetail:function(){
    var that = this;
    var goodId = that.data.goodId;
    var data = {
      map: 'applet_mall_group_detail',
      gbid: goodId
    }
    console.log(data);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var dataInfo = res.data.data;
          var showList = dataInfo.show_list;
          // console.log(showList);
          if (showList){
            for (var i = 0; i < showList.length; i++) {
              that.time(showList[i].left_time, showList, i);
            }
          }
          that.djsTime(showList);
          that.requestComment(dataInfo.detail.id);
          if (dataInfo.detail.video != '') {
            that.setData({
              video: dataInfo.detail.video,
              videoShow: true,
            })
          }
          /** 规格库存判断开始 **/
          if (dataInfo.detail.formatList && dataInfo.detail.formatList.length == 1) {
            for (let i in dataInfo.detail.formatList[0].value) {
              if (dataInfo.detail.formatValueNew[dataInfo.detail.formatList[0].value[i].name].stock == 0) {
                dataInfo.detail.formatList[0].value[i].noCheck = true;
              }
            }
          }
          that.setData({
            nogood:1,
            goodData: dataInfo,
            wxGroupData: dataInfo.wxGroupData,
            goodDetail: dataInfo.detail,
            formatList: dataInfo.detail.formatList ? dataInfo.detail.formatList:[],
            formatValue: dataInfo.detail.formatValueNew ? dataInfo.detail.formatValueNew:'',
            formatSection: dataInfo.detail.formatSection ? dataInfo.detail.formatSection:[],
            curformatSection: dataInfo.detail.formatSection && dataInfo.detail.formatSection[0] ? dataInfo.detail.formatSection[0] : '',
            total: dataInfo.detail.total,
            cartNumber: dataInfo.cartNum ? dataInfo.cartNum:'',
            hasFormat: dataInfo.detail.hasFormat,
            showList: showList,
            chooseGuige: {
              stock: dataInfo.detail.stock
            }
          })
          var article = that.data.goodDetail.detail;
          // 富文本解析
          WxParse.wxParse('article', 'html', article, that, 5);
          var rule = dataInfo.groupDesc.rule ? dataInfo.groupDesc.rule:'';
          WxParse.wxParse('rule', 'html', rule, that, 5);
        } else {
          app.errorTip(that, res.data.em, 2000);
          that.setData({
            nogood:0,
            tips: res.data.em
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  djsTime: function (showList){
    var that = this;
    // var showList = that.data.showList;
    console.log(showList);
    if (showList){
      for (var i = 0; i < showList.length; i++) {
        that.djs(showList[i].left_time, showList, i)
      }
    }
  },
  djs: function (time,showList,i) {
    var that = this;
    var leftTime = time;  //剩余秒数
    this.data.intervarID = setInterval(function () {
      // var leftTime = (tapTime * 1000) - (curTime.getTime()); //计算剩余的毫秒数 
      // var leftTime = tapTime * 1000; //计算剩余的毫秒数 
      leftTime--;
      that.time(leftTime, showList, i);
    }, 1000)
  },
  time: function (leftTime, showList, i){
    var that = this;
    if (leftTime > 0) {
      // var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 60 / 60, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime % 60, 10);//计算剩余的秒数 
      // days = days < 10 ? '0' + days : days;
      // console.log(days);
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      showList[i].hours = hours;
      showList[i].minutes = minutes;
      showList[i].seconds = seconds;
      that.setData({
        showList: showList
      })
      // console.log(that.data.showList)
      if (hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
      }
    } else {
      showList[i].hours = '00';
      showList[i].minutes = '00';
      showList[i].seconds = '00';
      that.setData({
        showList: showList
      })
    }
  },
  toggleBtn: function (e) {
    var that = this;
    var toggleType = e.currentTarget.dataset.toggletype;
    console.log(toggleType)
    that.setData({
      toggleType: toggleType
    })
  },
  backShouye: function () {
    app.backHome();
  },
  // backCart: function () {
  //   console.log("收藏成功")
  // },
  // chooseGuige: function (e) {
  //   var that = this;
  //   var findex = e.target.dataset.findex;
  //   var index = e.target.dataset.index;
  //   var formatList = that.data.formatList;
  //   var formatValue = that.data.formatValue;
  //   if (findex == 0) {
  //     var curImgformat = formatList[0].value[index];
  //     that.setData({
  //       curImgformat: curImgformat,
  //     })
  //   }
  //   var checkFormat = [];
  //   for (var i = 0; i < formatList[findex].value.length; i++) {
  //     formatList[findex].value[i].checked = false;
  //   }
  //   formatList[findex].value[index].checked = true;
  //   for (var i = 0; i < formatList.length; i++) {
  //     for (var j = 0; j < formatList[i].value.length; j++) {
  //       if (formatList[i].value[j].checked) {
  //         checkFormat.push(formatList[i].value[j]);
  //       }
  //     }
  //   }
  //   that.setData({
  //     formatList: formatList,
  //     checkFormat: checkFormat
  //   })
  //   if (checkFormat.length == formatList.length) {
  //     var formatName = '';
  //     for (var i = 0; i < checkFormat.length; i++) {
  //       formatName += checkFormat[i].name;
  //     }
  //     console.log(formatName);
  //     var chooseGuige = formatValue[formatName];
  //     chooseGuige.formatName = formatName;
  //     console.log(chooseGuige);
  //     that.setData({
  //       chooseGuige: chooseGuige
  //     })
  //   }
  // },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.currentTarget.dataset.findex;
    var index = e.currentTarget.dataset.index;
    var disabled = e.currentTarget.dataset.disabled;
    if (disabled) return;
    var formatList = that.data.formatList;
    var formatValue = that.data.formatValue;
    var checkFormat = [];
    for (var i = 0; i < formatList[findex].value.length; i++) {
      if (index == i) {
        formatList[findex].value[index].checked = !formatList[findex].value[index].checked;
        if (findex == 0 && formatList[findex].value[index].checked) {
          var curImgformat = formatList[0].value[index];
          that.setData({
            curImgformat: curImgformat
          })
        } else {
          if (findex == 0) {
            that.setData({
              curImgformat: ''
            })
          }
        }
      } else {
        formatList[findex].value[i].checked = false;
      }
    }
    for (var i = 0; i < formatList.length; i++) {
      for (var j = 0; j < formatList[i].value.length; j++) {
        if (formatList[i].value[j].checked) {
          checkFormat.push(formatList[i].value[j]);
        }
      }
    }
    /** 规格库存判断开始 **/
    for (let k in formatList) {
      for (let n in formatList[k].value) {
        formatList[k].value[n].noCheck = false
      }
    }

    for (let i in formatValue) {
      let noStockArr = [];
      let formatValueItem = i.split('-');
      switch (checkFormat.length) {
        case 1:
          if (formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValue[i]['stock'] == 0 && formatList.length == 2) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            noStockArr = formatValueItem;
          } else if (formatValue[i]['stock'] == 0 && formatList.length == 1) {
            noStockArr.push(i);
          } else if (formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValue[i]['stock'] == 0 && formatList.length == 3) {
            noStockArr = [];
          }
          break;
        case 2:
          if ((formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValueItem.indexOf(checkFormat[1].name) != -1) && formatValue[i]['stock'] == 0 && formatList.length == 3) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            noStockArr = formatValueItem;
          } else if ((formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1) && formatValue[i]['stock'] == 0 && formatList.length == 2) {
            if (formatValueItem.indexOf(checkFormat[0].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            }
            if (formatValueItem.indexOf(checkFormat[1].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            }
            noStockArr = formatValueItem;
          }
          // console.log(noStockArr);
          break;
        case 3:
          if (formatValue[i]['stock'] == 0 && (formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1 || formatValueItem.indexOf(checkFormat[2].name) != -1)) {
            for (let q in checkFormat) {
              formatValueItem[formatValueItem.indexOf(checkFormat[q].name)] = '';
            }
            if (formatValueItem[0] === '') {
              formatValueItem[1] = formatValueItem[2] = formatValueItem[1] + formatValueItem[2]
            }
            if (formatValueItem[1] === '') {
              formatValueItem[0] = formatValueItem[2] = formatValueItem[0] + formatValueItem[2]
            }
            if (formatValueItem[2] === '') {
              formatValueItem[0] = formatValueItem[1] = formatValueItem[0] + formatValueItem[1]
            }
            console.log(formatValueItem);
            noStockArr = formatValueItem
          }
          break;
      }
      console.log(noStockArr);
      for (let k in formatList) {
        for (let n in formatList[k].value) {
          if (noStockArr.indexOf(formatList[k].value[n].name) != -1) {
            formatList[k].value[n].noCheck = true
          }
        }
      }
    }
    // 单规格库存判断
    if (formatList.length == 1) {
      for (let i in formatList[0].value) {
        if (formatValue[formatList[0].value[i].name].stock == 0) {
          formatList[0].value[i].noCheck = true;
        }
      }
    }
    /** 规格库存判断结束 **/
    console.log(formatList);
    that.setData({
      formatList: formatList,
      checkFormat: checkFormat
    })
    if (checkFormat.length == formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
        if (i < checkFormat.length - 1) {
          formatName += '-';
        }
      }
      console.log(formatName);
      console.log(formatValue);
      var chooseGuige = formatValue[formatName];
      chooseGuige.formatName = formatName;
      // chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    } else {
      that.setData({
        chooseGuige: {
          stock: that.data.goodDetail.stock
        }
      })
    }
  },
  chooseformatSection:function(e){
    var that = this;
    var curformatSection = e.currentTarget.dataset.formatsection;
    that.setData({
      curformatSection: curformatSection,
      formatList: curformatSection.formatList ? curformatSection.formatList:[],
      formatValue: curformatSection.formatValueNew ? curformatSection.formatValueNew:[],
      chooseGuige: {
        stock: that.data.goodDetail.stock
      }
    })
  },
  nowbuy: function (e) {
    var that = this;
    if (app.globalData.slient == 1||(this.data.isHasunionid == 0 && this.data.haveVcmCard == 1)) {
      return;
    }
    var single = e.currentTarget.dataset.single;
    var type = e.currentTarget.dataset.type;
    console.log(type)
    that.setData({
      single: single,
      type: type ? type:'',
      isShowModal: true,
      modalOperaType: "buy"
    })
  },
  hideModal: function () {
    var that = this;
    that.setData({
      isShowModal: false
    })
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var stock = that.data.chooseGuige.stock;
    console.log(stock);
    
    var buyNum = parseInt(that.data.buyNumber);
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
        return;
      }
      if (buyNum < stock){
        buyNum++;
      }else{
        buyNum = stock;
      }
    } else {
      if (buyNum > 1) {
        buyNum--;
      } else {
        buyNum = 1;
      }
    }
    that.setData({
      buyNumber: buyNum
    })
  },
  confirmAddcart: function (e) {
    var that = this;
    var suid = app.globalData.suid;
    var gid = e.target.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = that.data.buyNumber;
    var isFormat = that.data.hasFormat;
    var stock = that.data.chooseGuige.stock;
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num
    }
    if (stock < num){
      app.errorTip(that, '商品库存不足', 2000);
      return;
    }
    if (isFormat && !data.gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
    } else {
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          if (res.data.ec == 200) {
            wx.showToast({
              title: res.data.data.msg,
              icon: 'success',
              duration: 2000,
            })
            that.hideModal();
            that.setData({
              cartNumber: res.data.data.cartNum
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.em,
              showCancel: false
            });
          }
        },
        complete: function () {
        }
      });
    }
  },
  joinGrounp:function(e){
    var that = this;
    var tid = e.currentTarget.dataset.tid;
    var actid = e.currentTarget.dataset.actid;
    console.log(actid)
    var goodid = e.currentTarget.dataset.goodid;
    console.log(goodid);
    var goodstock = e.currentTarget.dataset.stock;
    console.log(goodstock)
    console.log(tid)
    wx.navigateTo({
      url: '/subpages/joinGroup/joinGroup?tid=' + tid + '&actid=' + actid + '&goodid=' + goodid + '&goodstock=' + goodstock,
    })
  },
  nextStep: function () {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var gfid = that.data.chooseGuige.id;
    var isFormat = that.data.hasFormat;
    var orderArr = [];
    var orderObj = {};
    var extra = {};
    if(that.data.type){
      if (that.data.goodDetail.gbtype == 4){
        extra.type = that.data.type;
        extra.actid = that.data.curformatSection && that.data.curformatSection.actId ? that.data.curformatSection.actId:'';
        if (!extra.actid){
          app.errorTip(that, '请选择团购人数', 2000);
          return;
        }
      }else{
        extra.type = that.data.type;
        extra.actid = that.data.goodId;
      }
    }
    orderObj.gid = that.data.goodDetail.id;
    orderObj.gfid = that.data.chooseGuige.id;;
    orderObj.num = that.data.buyNumber;
    orderArr.push(orderObj);
    var data = {};
    data.map ='applet_order_create';
    data.extra = extra ? extra : '';
    data.buys = encodeURI(JSON.stringify(orderArr));
    console.log(data)
    console.log(app.globalData.requestUrl);
    if (stock < orderObj.num) {
      app.errorTip(that, '商品库存不足', 2000);
      return;
    }
    if (isFormat && !gfid){
      app.errorTip(that, '请选择商品规格！', 2000);
    }else{
      //发起请求，获取列表列表
      wx.showLoading({
        title: '加载中',
      })
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          console.log(res.data);
          if (res.data.ec == 200) {
            console.log(res.data.data);
            wx.setStorage({
              key: "submitOrder",
              data: res.data.data,
              success: function () {
                var type = that.data.type ? that.data.type : ''
                wx.navigateTo({
                  url: '/pages/waitBuyerPay/waitBuyerPay?type='+type
                })
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.em,
              showCancel: false
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    }
  },
  requestComment: function (goodId) {
    var that = this;
    //发起请求，获取列表列表
    if (!that.data.goodDetail) {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_goods_comment_list',
        gid: goodId
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          that.setData({
            commentNum: res.data.data.total,
            commentList: res.data.data.list
          })
          console.log(that.data.commentList)
        } else {
          console.log(res.data);
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  toEvaluateList: function () {
    var that = this;
    var goodid = that.data.goodDetail.id;
    wx.navigateTo({
      url: '/pages/evaluateList/evaluateList?goodid=' + goodid
    })
  },
  peiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = e.currentTarget.dataset.imgs;
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  showSharemodal(){
    var pageShare = this.selectComponent('.page-share'), 
    posterData={map:'applet_goods_details_poster',gid:this.data.goodId,type: 'group'};
    console.log(posterData)
    this.setData({
      posterData:posterData
    })
    pageShare.showSharemodal()
  },
  hideSharemodal(){
    var pageShare = this.selectComponent('.page-share');
    pageShare.hideSharemodal()
  },
  toGoodparameter: function (e) {
    var parameter = e.currentTarget.dataset.param;
    wx.setStorage({
      key: "goodParameter",
      data: parameter,
      success: function () {
        wx.navigateTo({
          url: '/subpages/goodParameter/goodParameter',
        })
      }
    })
  },
  // VR视图
  toWebview: function (e) {
    var that = this;
    var vrurl = e.currentTarget.dataset.vrurl;
    var cover = e.currentTarget.dataset.cover;
    var title = e.currentTarget.dataset.title;
    var vrInfo = {
      vrurl: vrurl,
      cover: cover ? cover : '',
      title: title ? title : ''
    }
    wx.setStorage({
      key: 'webviewUrl',
      data: vrInfo,
      success: function () {
        wx.navigateTo({
          url: '/pages/commonView/commonView',
        })
      }
    })
  },
  hideGetuser: function () {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  onShareAppMessage: function () {
    var that = this;
    var mid = app.globalData.userInfo.mid;
    var goodid = that.data.goodId;
    var title = that.data.goodData.share && that.data.goodData.share.title ? that.data.goodData.share.title : '';
    var img = that.data.goodData.share && that.data.goodData.share.img ? that.data.goodData.share.img : '';
    if (!title){
      title = that.data.goodDetail.name;
    }
    that.hideSharemodal();
    app.getPoint(that);
    return {
      title: title,
      path: '/pages/groupGoodDetail/groupGoodDetail?enterfrom=share&goodid=' + goodid + '&mid=' + mid,
      imageUrl: img
    }
  },
})